/*
 * This file is part of the SDWebImage package.
 * (c) Olivier Poitrey <rs@dailymotion.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import "UIImageView+WebCache.h"
#import "SDWebImageManager.h"
#import "DownloadImageManager.h"
#import <CommonCrypto/CommonHMAC.h>
#import "WeatherDefines.h"
#import "ASINetworkQueue.h"
#import "SDImageCache.h"
#import "Util.h"
#import "LoadingView.h"

@implementation UIImageView (WebCache)



- (void)setImageWithURL:(NSURL *)url
{
    [self setImageWithURL:url placeholderImage:nil subDirectory:nil];
    
}

#pragma mark file process
NSString* fileNameFromURL(NSString* url)
{
    NSArray *arr = [url componentsSeparatedByString:@"/"];
    return [arr lastObject];
}

BOOL isFileExist(NSString* path)
{
    return  [[NSFileManager defaultManager] fileExistsAtPath:path];
}

void removePath(NSString* path)
{
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
void createDirectory(NSString* path)
{
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
}

BOOL isDirectoryExist(NSString* path)
{    
    BOOL is = NO;
    if([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&is])
        return YES;
    return NO;
}

NSString* MD5String(NSString* key)
{
    const char *str = [key UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *md5 = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                     r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    return md5;
    
}
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder subDirectory:(NSString*)subDirectory
{
    
     SDWebImageManager *manager = [SDWebImageManager sharedManager];
     
     // Remove in progress downloader from queue
     [manager cancelForDelegate:self];
     
     UIActivityIndicatorView *activityView = [[[UIActivityIndicatorView alloc]
     initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];

     activityView.frame = CGRectMake(self.frame.size.width/2 -11 ,self.frame.size.height/2 -11, 22.0f, 22.0f);
      
     activityView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
     UIViewAutoresizingFlexibleBottomMargin |
     UIViewAutoresizingFlexibleLeftMargin |
     UIViewAutoresizingFlexibleTopMargin;
     
     [self addSubview: activityView];
    
  
     
    NSString *str = [[CACHE_IMAGE_DIR copy] autorelease];
    
    if(!isDirectoryExist(str)){
        createDirectory(str);
    }
    
    
    int requestTag;
    if(subDirectory != nil && ![subDirectory isEqualToString:@""]){
        NSArray *arrComponent = [subDirectory componentsSeparatedByString:@"/"];
        if([arrComponent count] > 0){
            requestTag = [[arrComponent objectAtIndex:0] intValue];
            for( int i =0; i < [arrComponent count]; i++){
                if(![[arrComponent objectAtIndex:i] isEqualToString:@""]){
                    str = [str stringByAppendingFormat:@"%@/",[arrComponent objectAtIndex:i]];
                    if(!isDirectoryExist(str))
                        createDirectory(str);
                }
            }
        }
    }
    
 

    NSString* path = [NSString stringWithFormat:@"%@%@",str,MD5String([url absoluteString])];
    
    NSLog(@"Link %@",path);
      NSLog(@"Link %@",str);
       
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        if(image != nil){
            self.image = image;

            return;
        }

    
    [activityView startAnimating]; 
       
     if (url)
     {
         [manager downloadWithURL:url delegate:self retryFailed:NO lowPriority:NO defaultImage:placeholder path:path];
     }
        
}

- (void)setImageWithURL:(NSURL *)url defaultImage:(UIImage *)defaultImage timeOut:(int)timeOut
{
    
    self.image = nil;
    [self removeIndicator];
    if(!isDirectoryExist(CACHE_IMAGE_DIR))
    {
        createDirectory(CACHE_IMAGE_DIR);
    }
    NSString* path = [NSString stringWithFormat:@"%@%@",CACHE_IMAGE_DIR,MD5String([url absoluteString])];
    if(isFileExist(path))
    {        
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        self.image = image;     
        return;
    }    
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];    
    activityView.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);            
    [self addSubview: activityView];
    [activityView release];
    [activityView startAnimating];     
    
 
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        bool isRequestSuccess = NO;
        ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
        request.downloadDestinationPath = path;
        request.temporaryFileDownloadPath = [NSString stringWithFormat:@"%@temp",path];
        [request setAllowResumeForFileDownloads:YES];
        [request setTimeOutSeconds:timeOut];
        
        BOOL is_download = [[DownloadImageManager Shared] downloadWithObject:request];
        if(!is_download)
        {
            [self removeIndicator];
            SAFE_RELEASE(request);
            
            return;
        }
        NSError *error = nil;
        for(int i = 0; i<2 && !isRequestSuccess; i++)
        {            
            [request startSynchronous];   
            
            error = [request error];
            SAFE_RELEASE(request);
            
            if (error == nil) {
                
                dispatch_async(dispatch_get_main_queue(), ^{  
                    [request clearDelegatesAndCancel];
                    [self removeIndicator];
                    UIImage *image = [UIImage imageWithContentsOfFile:path];
                    self.image = image; 
                });
                isRequestSuccess = YES;
            }
            else {
               
                if(error.code==8)
                {
                    if(i == 1)
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self removeIndicator];
                            [request clearDelegatesAndCancel];
                            NSData *data = UIImagePNGRepresentation(defaultImage);
                            [data writeToFile:path atomically:YES];
                            UIImage *image = [UIImage imageWithContentsOfFile:path];
                            self.image = image;  
                        });
                    }
                    else
                    {
                        
                    }
                }
                
            }
        }   
    });    
    
}

- (void)setImageWithURL02:(NSURL *)url defaultImage:(UIImage *)defaultImage timeOut:(int)timeOut index:(NSInteger)index
{
       
   NSNumber *_index = [NSNumber numberWithUnsignedInt:index];
    self.image = nil;
    [self removeIndicator];
    if(!isDirectoryExist(CACHE_IMAGE_DIR02))
    {
        createDirectory(CACHE_IMAGE_DIR02);
    }
    NSString* path = [NSString stringWithFormat:@"%@%@",CACHE_IMAGE_DIR02,MD5String([url absoluteString])];
    if(isFileExist(path))
    {        
        UIImage *image =[UIImage imageWithContentsOfFile:path];
        self.image = image; 
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sortScrollView" object:_index];
        return;
    }    
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];    
    activityView.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);            
    [self addSubview: activityView];
    [activityView release];
    [activityView startAnimating];     
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        
        ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
        request.downloadDestinationPath = path;
        request.temporaryFileDownloadPath = [NSString stringWithFormat:@"%@temp",path];
        [request setAllowResumeForFileDownloads:YES];
        [request setTimeOutSeconds:timeOut];
        
        BOOL is_download = [[DownloadImageManager Shared] downloadWithObject:request];
        if(!is_download)
        {
            [self removeIndicator];
            SAFE_RELEASE(request);
            
            return;
        }            
        
        [request startSynchronous];   
        NSError *error = [request error];
        SAFE_RELEASE(request);
        
        if (error == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{  
                [request clearDelegatesAndCancel];
                [self removeIndicator];
                UIImage *image =[UIImage imageWithContentsOfFile:path];
                self.image =image;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"sortScrollView" object:_index];
            });
        }
        else {
           
            if(error.code==8)
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self removeIndicator];
                    [request clearDelegatesAndCancel];
                    NSData *data = UIImagePNGRepresentation(defaultImage);
                    [data writeToFile:path atomically:YES];
                    UIImage *image =[UIImage imageWithContentsOfFile:path];
                    self.image =image;
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"sortScrollView" object:_index];
                });
            }
            
        }
        
    });    
    
}

-(UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)targetSize {
    
    CGFloat scaleFactor = 1.0;
    if (image.size.width != targetSize.width){
        scaleFactor = (targetSize.width / image.size.width);
    }
    UIGraphicsBeginImageContext(CGSizeMake(320, image.size.height * scaleFactor==0?320:image.size.height * scaleFactor));
    float yLocation=image.size.height * scaleFactor<=320?(320-image.size.height * scaleFactor)/2:0;
    CGRect rect = CGRectMake(0,yLocation,image.size.width * scaleFactor, image.size.height * scaleFactor);
    [image drawInRect:rect];
    
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}



#pragma mark -
#pragma mark ASINetworkQueue delegate methods

- (void)requestDone:(ASIHTTPRequest *)request
{
    if(self != nil)
    {
        [self removeIndicator];
        NSData *data = [request responseData];
        UIImage *remoteImage = [[UIImage alloc] initWithData:data];
        self.image = remoteImage;
        
    }
}

- (void)requestWentWrong:(ASIHTTPRequest *)request
{
    if(self != nil)
    {
        [self removeIndicator];
    }
}


- (void) downloadImageSuccess:(ASIHTTPRequest *)request {
    
}

- (void) downloadImageFail:(ASIHTTPRequest *)request {
  }

- (void)setImageWithURL2:(NSURL *)url defaultImage:(UIImage *)defaultImage timeOut:(int)timeOut subDirectory:(NSString*)subDirectory index:(NSInteger)index
{
    NSNumber *_index = [NSNumber numberWithUnsignedInt:index];
    SDWebImageManager *manager = [SDWebImageManager sharedManager];   
    [manager cancelForDelegate:self];
    UIActivityIndicatorView *activityView = [[[UIActivityIndicatorView alloc]
                                              initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];    
    activityView.frame = CGRectMake(self.frame.size.width/2 -11 ,self.frame.size.height/2 -11, 22.0f, 22.0f);    
    activityView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
    UIViewAutoresizingFlexibleBottomMargin |
    UIViewAutoresizingFlexibleLeftMargin |
    UIViewAutoresizingFlexibleTopMargin;
    
    [self addSubview: activityView];
    
    
    NSString *str = [[CACHE_IMAGE_DIR copy] autorelease];
    
    if(!isDirectoryExist(str)){
        createDirectory(str);
    }
    
    
    int requestTag;
    if(subDirectory != nil && ![subDirectory isEqualToString:@""]){
        NSArray *arrComponent = [subDirectory componentsSeparatedByString:@"/"];
        if([arrComponent count] > 0){
            requestTag = [[arrComponent objectAtIndex:0] intValue];
            for( int i =0; i < [arrComponent count]; i++){
                if(![[arrComponent objectAtIndex:i] isEqualToString:@""]){
                    str = [str stringByAppendingFormat:@"%@/",[arrComponent objectAtIndex:i]];
                    if(!isDirectoryExist(str))
                        createDirectory(str);
                }
            }
        }
    }
    
    
    NSString* path = [NSString stringWithFormat:@"%@%@",str,MD5String([url absoluteString])];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    if(image != nil){
        self.image = image;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sortScrollView" object:_index];
        return;
    }
    
    [activityView startAnimating];
    
    if (url)
    {
        [manager downloadWithURL:url delegate:self retryFailed:NO lowPriority:NO defaultImage:defaultImage path:path];
    }
}
-(BOOL)checkImageCacheWithUrl:(NSURL*)url andDir:(NSString*)subDirectory{
    NSString *str = [[CACHE_IMAGE_DIR copy] autorelease];
    
    if(!isDirectoryExist(str)){
        return NO;
    }
    
    
    int requestTag;
    if(subDirectory != nil && ![subDirectory isEqualToString:@""]){
        NSArray *arrComponent = [subDirectory componentsSeparatedByString:@"/"];
        if([arrComponent count] > 0){
            requestTag = [[arrComponent objectAtIndex:0] intValue];
            for( int i =0; i < [arrComponent count]; i++){
                if(![[arrComponent objectAtIndex:i] isEqualToString:@""]){
                    str = [str stringByAppendingFormat:@"%@/",[arrComponent objectAtIndex:i]];
                    if(!isDirectoryExist(str))
                        return NO;
                }
            }
        }
    }
    NSString* path = [NSString stringWithFormat:@"%@%@",str,MD5String([url absoluteString])];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        if(image != nil){
            self.image = image;     
            return YES;
        }
    return NO;
}

- (void)setImageWithURL:(NSURL *)url defaultImage:(UIImage *)defaultImage timeOut:(int)timeOut subDirectory:(NSString*)subDirectory
{
 
    [self setImageWithURL:url placeholderImage:defaultImage subDirectory:subDirectory];
    

}



- (void)setImageWithURLInScroll:(NSURL *)url defaultImage:(UIImage *)defaultImage timeOut:(int)timeOut subDirectory:(NSString*)subDirectory
{
   
    self.image = nil;
    [self removeIndicator];
    
    
    NSString *str = [[CACHE_IMAGE_DIR copy] autorelease];
    
    if(!isDirectoryExist(str)){
        createDirectory(str);
    }
    int requestTag;
    if(subDirectory != nil && ![subDirectory isEqualToString:@""]){
        NSArray *arrComponent = [subDirectory componentsSeparatedByString:@"/"];
        if([arrComponent count] > 0){
            requestTag = [[arrComponent objectAtIndex:0] intValue];
            for( int i =0; i < [arrComponent count]; i++){
                if(![[arrComponent objectAtIndex:i] isEqualToString:@""]){
                    str = [str stringByAppendingFormat:@"%@/",[arrComponent objectAtIndex:i]];
                    if(!isDirectoryExist(str))
                        createDirectory(str);
                }
            }
            
        }
    }
    
    
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];    
    activityView.frame = CGRectMake(self.frame.size.width/2 -11 ,self.frame.size.height/2 -11, 22.0f, 22.0f);
    
    activityView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
    UIViewAutoresizingFlexibleBottomMargin |
    UIViewAutoresizingFlexibleLeftMargin |
    UIViewAutoresizingFlexibleTopMargin;
    [self addSubview: activityView];
    
    NSString* path = [NSString stringWithFormat:@"%@%@",str,MD5String([url absoluteString])];
    if(isFileExist(path))
    {        
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        if(image == nil){

        }
        else {
            self.image = image;     
            return;
        }
        
    }
    
    [activityView startAnimating]; 
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        
        ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
        request.downloadDestinationPath = path;
        request.temporaryFileDownloadPath = [NSString stringWithFormat:@"%@temp",path];
        [request setAllowResumeForFileDownloads:YES];
        [request setTimeOutSeconds:10000];
        
        BOOL is_download = [[DownloadImageManager Shared] downloadWithObject:request];
        if(!is_download)
        {
        }
        
        
        request.tag = requestTag;
        [request startSynchronous];

        
        NSError *error = [request error];
        
        
        if (error == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{  
                
                
                UIImage *image = [UIImage imageWithContentsOfFile:path];
                if(image != nil){
                    [request clearDelegatesAndCancel];
                    [self removeIndicator];
                    self.image = image;
                }
                else {
                   
                    [self removeIndicator];
                    NSData *data = UIImagePNGRepresentation(defaultImage);
                    [data writeToFile:path atomically:YES];
                    UIImage *image = [UIImage imageWithContentsOfFile:path];
                    self.image = image;
                }
            });
        }
        else {
                     
            if(error.code==8)
            {
                dispatch_async(dispatch_get_main_queue(), ^{  
                    [self removeIndicator];
                    [request clearDelegatesAndCancel];
                    NSData *data = UIImagePNGRepresentation(defaultImage);
                    [data writeToFile:path atomically:YES];
                    UIImage *image = [UIImage imageWithContentsOfFile:path];
                    self.image = image;
                });
            }
            
        }
        
    });    
    
}

-(void)removeIndicator
{
    for (UIView *view  in self.subviews)
    {
        if([view class] == [UIActivityIndicatorView class])
        {
            UIActivityIndicatorView *activityView = (UIActivityIndicatorView*)view;
            [activityView stopAnimating];
            [view removeFromSuperview];
        }
        
        else if ([view isKindOfClass:[LoadingView class]])
        {
            [view removeFromSuperview];
        }
        
        
    }
}
-(void)setTimeout:(int)time{

}
-(void) setTimeout:(int)time withImage:(UIImage *)image{

}

-(void)setTimeoutAndCancelDuration:(int)time{
    [self performSelector:@selector(checkTimeOutAfterDelay) withObject:nil afterDelay:time];
}
-(void)checkTimeout{
    NSArray *subviews = [self subviews];
    UIActivityIndicatorView *activityView = nil;
    for (activityView in subviews)
    {
        if ([activityView isKindOfClass:[UIActivityIndicatorView class]])
        {
            [activityView stopAnimating];
            [activityView removeFromSuperview];
        }
              else if ([activityView isKindOfClass:[LoadingView class]])
        {
            [activityView removeFromSuperview];
        }
       
    }
   
}

- (void)checkTimeout:(UIImage *)image{

}

-(void)checkTimeOutAfterDelay{
    DebugLog(@"checkTimeOutAfterDelay");
     NSArray *subviews = [self subviews];
    for (UIActivityIndicatorView *activityView  in subviews)
    {
        if ([activityView isAnimating]) {
                [activityView stopAnimating];
                
            
            NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",self.tag],@"index", nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadError" object:nil userInfo:userInfo];

            break;
        }
    }
     
    
}


- (void)cancelCurrentImageLoad
{
    // added by seng
    NSArray *subviews = [self subviews];
    UIActivityIndicatorView *activityView = nil;
    for (activityView in subviews)
    {
        if ([activityView isKindOfClass:[UIActivityIndicatorView class]])
        {
            [activityView stopAnimating];
            [activityView removeFromSuperview];
        }
       
        else if ([activityView isKindOfClass:[LoadingView class]])
        {
            [activityView removeFromSuperview];
        }
      
    }

    [[SDWebImageManager sharedManager] cancelForDelegate:self];
}
- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image
{
    
        self.image = image;
  
    
    
    NSArray *subviews = [self subviews];
    UIActivityIndicatorView *activityView = nil;
    for (activityView in subviews)
    {
        if ([activityView isKindOfClass:[UIActivityIndicatorView class]])
        {
            [activityView stopAnimating];
            [activityView removeFromSuperview];
        }
        
        else if ([activityView isKindOfClass:[LoadingView class]])
        {
            [activityView removeFromSuperview];
        }
    }

        
}



-(void)webImageManager:(SDWebImageManager *)imageManager didFailWithError:(NSError *)error{
   
    NSArray *subviews = [self subviews];
    UIActivityIndicatorView *activityView = nil;
    for (activityView in subviews)
    {
        if ([activityView isKindOfClass:[UIActivityIndicatorView class]])
        {
            [activityView stopAnimating];
            [activityView removeFromSuperview];
        }
       
        else if ([activityView isKindOfClass:[LoadingView class]])
        {
            [activityView removeFromSuperview];
        }
   
    }

    
    if(!self.image){
         NSLog(@"TAG FAIL = %d", self.tag);
        NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",self.tag],@"index", nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadError" object:nil userInfo:userInfo];
    }
    else{
        UIImageView *imageTemp = [[UIImageView alloc]initWithImage:self.image];
        imageTemp.tag = self.tag;
        NSLog(@"TAG = %d", self.tag);
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"FinishDownloadImage" object:imageTemp userInfo:nil];
        

    }
       
}

@end
